﻿using System.Configuration;
using System.IO;
namespace Common
{
    public class GenneralConfig
    {
      //  string path = Path.GetFullPath(string.Format("./Configs/{0}.xml", CurrentModel));
        /// <summary>
        /// 当前机种的设置
        /// </summary>
        public ModuleConfig module { get; set; }
        private GenneralConfig() {
            string path=Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory+string.Format("Configs/{0}.xml", CurrentModel));
            if (!File.Exists(path))
            {
                string path2 = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory+string.Format("Configs/{0}.xml", "template"));
                var obj = ConfigEx.DeserializeFromXml<ModuleConfig>(path2);
                obj.SerializeToXml(path);
            }
            module = ConfigEx.DeserializeFromXml<ModuleConfig>(string.Format(path));
        }
        public static readonly GenneralConfig instance = new GenneralConfig();

        #region 工单 MO
        /// <summary>
        /// 工单属性
        /// </summary>
        public string MO { get { return getMO(); } set { setMO(value); } }
        private string getMO()
        {
            return AppConfigEx.GetConfigValue("MO");
        }
        private void setMO(string Value)
        {
            AppConfigEx.SetConfigValue("MO", Value);
        }
        #endregion

        #region 操作员工号 OperID
        /// <summary>
        /// 操作员工号
        /// </summary>
        public string OperID { get { return getOperID(); } set { setOperID(value); } }
        private string getOperID()
        {
            return AppConfigEx.GetConfigValue("Operator");
        }
        private void setOperID(string Value)
        {
            AppConfigEx.SetConfigValue("Operator", Value);
        }
        #endregion

        #region 机种列表 ModuleList
        /// <summary>
        /// 机种列表
        /// </summary>
        public string[] ModuleList { get { return getModuleList(); } set { setModuleList(value); } }
        private string[] getModuleList()
        {
            return AppConfigEx.GetConfigValue("ModelList").Split(',');
        }
        private void setModuleList(string[] Value)
        {
            AppConfigEx.SetConfigValue("ModelList", string.Join(",",Value));
        }
        #endregion

        #region 当前机种 CurrentModel
        /// <summary>
        /// 当前机种
        /// </summary>
        public string CurrentModel { get { return getCurrentModel(); } set { setCurrentModel(value); } }
        private string getCurrentModel()
        {
            return AppConfigEx.GetConfigValue("CurrentModel");
        }
        private void setCurrentModel(string Value)
        {
            AppConfigEx.SetConfigValue("CurrentModel", Value);
        }
        #endregion

        #region 当前使用的IO卡 IO type
        /// <summary>
        /// 当前使用的IO卡
        /// </summary>
        public int IO_TYPE { get { return getIO_TYPE(); } set { setIO_TYPE(value); } }
        private int getIO_TYPE()
        {
            return int.Parse(AppConfigEx.GetConfigValue("IO_TYPE"));
        }
        private void setIO_TYPE(int Value)
        {
            AppConfigEx.SetConfigValue("IO_TYPE", Value.ToString());
        }
        #endregion



        public void SaveModuleConfig()
        {
            module.SerializeToXml(Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory+string.Format("Configs/{0}.xml", CurrentModel)));
        }

        public void LoadModuleConfig()
        {
            string path = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory+string.Format("Configs/{0}.xml", CurrentModel));
            if (!File.Exists(path))
            {
                string path2 = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory + string.Format("Configs/{0}.xml", "template"));
                if (File.Exists(path2))
                {
                    var obj = ConfigEx.DeserializeFromXml<ModuleConfig>(path2);
                    obj.SerializeToXml(path);
                }
                else
                {
                    var obj = new ModuleConfig();
                    obj.SerializeToXml(path);
                }
            }
            module = ConfigEx.DeserializeFromXml<ModuleConfig>(string.Format(path));
        }

        #region 输出路径 Output Path
        /// <summary>
        /// 输出路径
        /// </summary>
        [DefaultSettingValue("D:\\Measure Data")]
        public string OutputPath { get { return getOutputPath(); } set { setOutputPath(value); } }
        private string getOutputPath()
        {
            return AppConfigEx.GetConfigValue("OutputPath");
        }
        private void setOutputPath(string Value)
        {
            AppConfigEx.SetConfigValue("OutputPath", Value);
        }
        #endregion

        #region 报表生成时间 ReportTime
        /// <summary>
        /// 报表生成时间
        /// </summary>
        [DefaultSettingValue("00:00:00")]
        public string ExportXlsxTime { get { return getExportXlsxTime(); } set { setExportXlsxTime(value); } }
        private string getExportXlsxTime()
        {
            return AppConfigEx.GetConfigValue("ExportXlsxTime");
        }
        private void setExportXlsxTime(string Value)
        {
            AppConfigEx.SetConfigValue("ExportXlsxTime", Value);
        }
        #endregion

        #region 设备号 MachineNo
        /// <summary>
        /// 设备号
        /// </summary>
        public string MachineNo { get { return getMachineNo(); } set { setMachineNo(value); } }
        private string getMachineNo()
        {
            return AppConfigEx.GetConfigValue("MachineNo");
        }
        private void setMachineNo(string Value)
        {
            AppConfigEx.SetConfigValue("MachineNo", Value);
        }
        #endregion

    }
    public static class AppConfigEx
    {
        #region 修改AppSettings中配置 SetConfigValue(string key, string value)
        /// <summary>
        /// 修改AppSettings中配置
        /// </summary>
        /// <param name="key">key值</param>
        /// <param name="value">相应值</param>
        public static bool SetConfigValue(string key, string value)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings[key] != null)
                    config.AppSettings.Settings[key].Value = value;
                else
                    config.AppSettings.Settings.Add(key, value);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        } 
        #endregion

        #region 获取AppSettings中某一节点值 GetConfigValue(string key)
        /// <summary>
        /// 获取AppSettings中某一节点值
        /// </summary>
        /// <param name="key"></param>
        public static string GetConfigValue(string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
                return config.AppSettings.Settings[key].Value;
            else
                return string.Empty;
        } 
        #endregion

        #region 获取连接节点值 GetConnectionValue(string key)
        /// <summary>
        /// 获取连接节点值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConnectionValue(string key)
        {
            if (ConfigurationManager.ConnectionStrings[key] != null)
                return ConfigurationManager.ConnectionStrings[key].ConnectionString;
            return string.Empty;
        } 
        #endregion

        #region 更新或新建一条连接字符串 UpdateConnectionStringsConfig(string key, string conString) 
        /// <summary>
        /// 更新或新建一条连接字符串
        /// </summary>
        /// <param name="key"></param>
        /// <param name="conString"></param>
        public static void UpdateConnectionStringsConfig(string key, string conString)
        {
            bool isModified = false;    //记录该连接串是否已经存在 
            if (ConfigurationManager.ConnectionStrings[key] != null)
            {
                isModified = true;
            }
            //新建一个连接字符串实例 
            ConnectionStringSettings mySettings = new ConnectionStringSettings(key, conString);

            // 打开可执行的配置文件*.exe.config 
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 如果连接串已存在，首先删除它 
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(key);
            }
            // 将新的连接串添加到配置文件中. 
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改 
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("connectionStrings");
        } 
        #endregion

    }

}
